import store from '@/store'
import auth from './auth'
import * as types from '@/store/action-types.js'
export default {
    validateUser:async function(to,from,next){
        try {
            await store.dispatch('validateUser');
            if (to.name == "/login") {
              next('/')
            } else {
              next();
            }
          } catch (e) {
            let needLogin = to.matched.some(item => item.meta.needLogin);
            if (needLogin) {
              next('/login')
            } else {
              next();
            }
          }
    },
    profileAuth:async function(to,from,next){
      if (store.state.hasPermission && store.state.user.menuList) {
        if (!store.state.menuPermission) {
          let list = store.state.user.menuList.map(item => item.auth);//后端的权限路由
          let newRoutes = auth.filter(item => list.includes(item.name));//筛选出权限路由
          store.commit(types.SET_MENU_LIST)
          this.addRoutes(newRoutes);
          next({...to,replace:true});// 把需要的路由新增进去 ,是在下一轮才会生效  导航不会留下history记录
        }else{
          next();
        }
      } else {
          next()
      }
    }
}